var newVue = new Vue({
	el: "body",
	data: {
		username: "",
		phone: "",
		area: "",
		address: "",
		istrue: false //判断是否是无效手机号
	},
	created: function() {
		init();
		_this = this;
		verifyLogin(_this)
	},
	methods: {
		save: function() {
			_this.checkUsername()
			if(_this.istrue == true) {
				addAddress(_this)
			} else {}
		},
		checkPhone: function() {
			var phone = _this.phone;
			var reg = /^1[34578]\d{9}$/;
			if(reg.test(phone)) {
				_this.checkArea()
			} else {
				$.toast("手机号有误", "cancel", function(toast) {
					console.log(toast);
				});
			}
		},
		checkUsername: function() {
			if(_this.username.trim().length > 0) {
				_this.checkPhone()
			} else {
				$.toast("用户名有误", "cancel", function(toast) {
					console.log(toast);
				});
			}
		},
		checkArea: function() {
			if(_this.area.trim().length > 0) {
				_this.checkAddress()
			} else {
				$.toast("地区有误", "cancel", function(toast) {
					console.log(toast);
				});
			}
		},
		checkAddress: function() {
			if(_this.address.trim().length > 0) {
				_this.istrue = true
			} else {
				$.toast("地址有误", "cancel", function(toast) {
					console.log(toast);
				});
			}
		},

		myAddress: function() {
			location.href = "./address.html"
		}

	}
})

function addAddress(a) {
	var username = currentUser.attributes.username
	var query = new AV.Query('Address');
	query.equalTo("user", username);
	query.find().then(function(products) {
		if(products.length > 0) {
			var Product = AV.Object.extend('Address')
			var product = new Product();
			product.set('username', a.username);
			product.set('phone', a.phone);
			product.set('area', a.area);
			product.set('address', a.address);
			product.set('isDefault', "none");
			product.set('user', currentUser.attributes.username);
			product.save().then(function() {
				$.toast("保存成功", function() {
					console.log('close');
				});
			}, function(error) {
				alert("failure")
			});
		} else {
			var Product = AV.Object.extend('Address')
			var product = new Product();
			product.set('username', a.username);
			product.set('phone', a.phone);
			product.set('area', a.area);
			product.set('address', a.address);
			product.set('isDefault', "default");
			product.set('user', currentUser.attributes.username);
			product.save().then(function() {
				$.toast("保存成功", function() {
					console.log('close');
				});
			}, function(error) {
				alert("failure")
			});
		}
		a.username = ""
		a.phone = ""
		a.area = ""
		a.address = ""
		a.istrue = false
	}).catch(function(error) {
		console.log(JSON.stringify(error));
	});
}

function verifyLogin(a) {
	currentUser = AV.User.current();
	if(currentUser) {
		a.isLoading = false
	} else {
		location.href = "login.html?RetUrl=" + getPageUrl()
	}
}